<?php
/*     Description */


// TODO: Zend_Validate_Db_NoRecordExists actually does exactly the same as this validator
// and it even has the exclusion options ...

class Pldkp_Validate_UniqueEntry extends Zend_Validate_Abstract 
{
    
    const NOT_UNIQUE = 'entryNotUnique';

    protected $_messageTemplates = array(
        self::NOT_UNIQUE => 'The value already exists'
    );

    protected $table;
    protected $field;
    protected $unless;

    /**
     * Constructor of this validator
     *
     * The argument to this constructor is the third argument to the elements' addValidator
     * method.
     *
     * The unless paramter can be used to ingore a entry having a specific field value
     * <code>
     * // Will ignore row with id 4
     * $unless = array('id' => 4);
     * </code>
     *
     * @param string Name of table class
     * @param string Field name
     * @param array|null Array having unless statements as field name => field value
     */
    public function __construct($table, $field, $unless = null) 
    {
        $this->table = $table;
        $this->field = $field;
        $this->unless = $unless;
    }

    /**
     * Check if the element using this validator is valid
     *
     * This method will check if the value exist in table Table
     * under field FIELD, succeeds if the value does not exist
     * 
     * @param $value string
     * @param $context array All other elements from the form
     * @return boolean Returns true if the element is valid
     */
    public function isValid($value) 
    {
        $table = new $this->table();
        
        // Fail if a user with that name already exist
        $select = $table->select()->where($this->field .' = ?', $value);
        

        // Add unless terms if any was given
        if (is_array($this->unless)) {
            foreach ($this->unless as $unlessField => $unlessValue) {
               $select->where($unlessField .' != ?', $unlessValue);
            }
        }
        
        $row = $table->fetchRow( $select );
        if ($row != null) {
            $this->_error(self::NOT_UNIQUE);
            return false;
        }
        
        return true;        
    }
}